package com.runa.monitor.platinterface.extend.nb.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctg.ag.sdk.biz.AepDeviceCommandClient;
import com.ctg.ag.sdk.biz.AepDeviceManagementClient;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandRequest;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandResponse;
import com.ctg.ag.sdk.biz.aep_device_management.QueryDeviceRequest;
import com.ctg.ag.sdk.biz.aep_device_management.QueryDeviceResponse;
import com.ctg.ag.sdk.biz.aep_device_management.UpdateDeviceRequest;
import com.ctg.ag.sdk.biz.aep_device_management.UpdateDeviceResponse;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.iotplatform.client.NorthApiException;
import com.iotplatform.client.dto.CommandDTOV4;
import com.iotplatform.client.dto.NotifyDeviceDataChangedDTO;
import com.iotplatform.client.dto.PostDeviceCommandInDTO2;
import com.iotplatform.client.dto.PostDeviceCommandOutDTO2;
import com.iotplatform.client.invokeapi.SignalDelivery;
import com.iotplatform.utils.JsonUtil;
import com.runa.monitor.comm.constants.ResultConstants;
import com.runa.monitor.comm.dto.newComm.*;
import com.runa.monitor.comm.entity.*;
import com.runa.monitor.comm.pojo.NBOrder;
import com.runa.monitor.comm.pojo.Result;
import com.runa.monitor.platinterface.mqtt.MqttUtil;
import com.runa.monitor.platinterface.extend.nb.config.LKBMqttNbIotConfig;
import com.runa.monitor.platinterface.extend.nb.config.MqttNbIotConfig;
import com.runa.monitor.platinterface.extend.nb.config.NewMqttNbIotConfig;
import com.runa.monitor.platinterface.extend.nb.utils.LKBMqttPanelUtils;
import com.runa.monitor.platinterface.extend.nb.utils.MqttBuildValveUtils;
import com.runa.monitor.platinterface.extend.nb.utils.MqttSetUtils;
import com.runa.monitor.platinterface.extend.nb.utils.MqttTemperaturePressureUtils;
import com.runa.monitor.platinterface.extend.nb.vo.*;
import com.runa.monitor.platinterface.extend.nb.vo.buildmeter.BuildMeterDecode;
import com.runa.monitor.platinterface.extend.nb.vo.buildmeter.MqttBuildMeterDataVo;
import com.runa.monitor.platinterface.extend.nb.vo.lkb.DataReportDTO;
import com.runa.monitor.platinterface.extend.third.pojo.TemperaturePressureCurrentData;
import com.runa.monitor.platinterface.platService.RepositoryService;
import com.runa.monitor.platinterface.service.NbSendService;
import com.runa.persistence.DateUtil;
import com.runa.persistence.StringUtil;
import com.runa.persistence.repository.*;
import com.runa.persistence.service.CommNbCmdService;
import com.runa.persistence.util.LogUtil;
import com.runa.protocol.util.FaultUtil;
import com.runa.protocol.util.ByteUtil;
import com.runa.protocol.util.UtilTime;
import com.runa.rccprotocol.analysis.HDRXAnalysis;
import com.runa.rccprotocol.analysis.RunaEquDataAnalysis;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Executor;

@Slf4j
@Service
public class NbPlantService {

    @Resource
    private OldNbiotService oldNbiotService;

    @Resource
    private NbSendService nbSendService;

    @Resource
    private RepositoryService repositoryService;

    private static final BigDecimal threehundred = new BigDecimal("300");
    private static final BigDecimal ten = new BigDecimal("10");

    public void handleruna(String body) {
        log.info("接受到的瑞纳的数据：{}", body);
        NotifyDeviceDataChangedDTO param = JsonUtil.jsonString2SimpleObj(body, NotifyDeviceDataChangedDTO.class);
        String deviceId = param.getDeviceId();
        String serviceId = param.getService().getServiceId();
        SignalDelivery signalDelivery = new SignalDelivery(oldNbiotService.getClient());
        Date now = new Date();
        PostDeviceCommandOutDTO2 pdcOutDTO = postCommand(serviceId, now, signalDelivery, deviceId, null);
        log.debug("指令下发返回结果：{}", pdcOutDTO);
        try {
            saveData(param, now);
        } catch (Exception e) {
            log.info(JSONObject.toJSONString(param));
            log.error("瑞纳数据处理报错", e);
        }
        log.info("瑞纳处理数据成功");
    }

    private void saveData(NotifyDeviceDataChangedDTO param, Date now) {
        ObjectNode objectNode = param.getService().getData();
        JsonNode msgNode = objectNode.get("msg");
        String msgStr = msgNode.asText();
        Map<String, String> msgMap = toMap(msgStr);
        String serialNo = msgMap.get("id");
        String tem = msgMap.get("temp");
        if (StringUtils.isEmpty(tem)) {
            tem = msgMap.get("tc");
        }
        String equTime = msgMap.get("rtc"); //设备时间
        Date planTime = UtilTime.StringToDate(equTime, "yyyyMMddHHmmss");
        String stateCode = msgMap.get("sta"); //状态字
        String humidity = msgMap.get("humi"); //湿度
        String version = msgMap.get("ver"); //版本号
        String signalIntensity = msgMap.get("csq"); //信号强度
        String cardNumber = msgMap.get("ccid"); //卡号
        CommPanel commPanel = commPanelRepository.findOne(Example.of(CommPanel.builder().serial(serialNo).communicationType(2)
                .factoryName("瑞纳").build())).orElse(null);
        if (commPanel == null) {
            log.error("数据库无数据---" + JSON.toJSONString(param));
            return;
        }
//        TemperaturePanel temPeraturePanel = temperaturePanelDao.getTemPeraturePanelBySerialNo(serialNo);
//        if (null == temPeraturePanel) {
//            log.info("nb面板不存在，编号为：{}", serialNo);
//            return;
//        }
        BigDecimal temperature = null != tem ? new BigDecimal(tem) : null;
        PanelVO currentData = new PanelVO();
//        currentData.setTemperaturePanelId(temPeraturePanel.getUniqueId());
//        currentData.setFaults(faultMsg);
        currentData.setTemperature(temperature.floatValue());
        currentData.setSignal(signalIntensity);
        currentData.setPanelDate(planTime);
        currentData.setReadTime(now);
        currentData.setReadTime(now);
        if (null != temperature) {
            currentData.setTemperature(temperature.setScale(2, RoundingMode.HALF_UP).floatValue());
        }
        currentData.setStatus(stateCode);
//        currentData.setState(true);
//        upService.upTemperaturePanelData(currentData);
        AsynResult asynResult = new AsynResult();
        asynResult.setCode(ResultConstants.CODE_200);
        asynResult.setMsg(MqttUtil.successString);
//                asynResult.setSymbol("data");
//        asynResult.setTimestamp(UtilTime.addMinute(new Date(timestamp), -sampling * (length - i - 1)).getTime());
        asynResult.setContent(Collections.singleton(currentData));
        asynResult.setIdentity(commPanel.getId());
        MqttUtil.send(PanelVO.TOPIC, asynResult);
    }

    public static Map<String, String> toMap(String msg) {
        Map<String, String> map = new HashMap<>();
        String[] splitBycomma = msg.split(",");
        for (int i = 0; i < splitBycomma.length; i++) {
            String[] splitBycolon = splitBycomma[i].split(":");
            String key = splitBycolon[0];
            String value = splitBycolon[1];
            map.put(key, value);
        }
        return map;
    }

    private PostDeviceCommandOutDTO2 postCommand(String serviceId, Date now, SignalDelivery signalDelivery, String deviceId, String accessToken) {
        PostDeviceCommandInDTO2 pdcInDTO = new PostDeviceCommandInDTO2();
        pdcInDTO.setDeviceId(deviceId);
        pdcInDTO.setExpireTime(0);

        CommandDTOV4 cmd = new CommandDTOV4();
        cmd.setServiceId(serviceId);
        cmd.setMethod("sendmsg"); //"PUT" is the command name defined in the profile

        Map<String, Object> cmdParam = new LinkedHashMap<String, Object>();
        Map<String, Object> msg = new LinkedHashMap<String, Object>();

        msg.put("rtc", UtilTime.dateToString(now, "yyyyMMddHHmmss"));
        msg.put("period", 60);
        String msgStr = JSONObject.toJSONString(msg);
        msgStr = msgStr.replace("\"", "");
        msgStr = msgStr.substring(1, msgStr.length() - 1);
        int legth = msgStr.length();
        cmdParam.put("msg", msgStr);//"brightness" is the command parameter name defined in the profile
        cmdParam.put("msglen", legth);

        cmd.setParas(cmdParam);
        pdcInDTO.setCommand(cmd);

        try {
            return signalDelivery.postDeviceCommand(pdcInDTO, null, accessToken);
        } catch (NorthApiException e) {
            log.error("瑞纳命令下发出错", e);
        }
        return null;
    }


    public String receiveDataForjunCounty(String body) {
        JSONObject json = JSONObject.parseObject(body);
        JSONObject service = json.getJSONObject("service");
        JSONObject data = service.getJSONObject("data");
        RoomTemDataVO roomTemDataVO = JSON.toJavaObject(data, RoomTemDataVO.class);
        LogUtil.getLogAndInfo(roomTemDataVO.getSN(), "NB", body);
        //查询温度面板
        CommPanel panel = repositoryService.getCommPanelByNodeSerial(roomTemDataVO.getSN());
        if (panel == null) {
            log.info("根据编号：" + roomTemDataVO.getSN() + "未查询到温度面板");
            return null;
        }
        BigDecimal temperature = new BigDecimal(roomTemDataVO.getTEMP()).divide(BigDecimal.TEN).subtract(new BigDecimal(30));
        PanelVO panelVO = new PanelVO();
        panelVO.setSerial(roomTemDataVO.getSN());
        panelVO.setReadTime(new Date());
        panelVO.setTemperature(temperature.floatValue());
        panelVO.setSignal(String.valueOf(roomTemDataVO.getCSQ()));
        AsynResult asynResult = new AsynResult();
        asynResult.setCode(ResultConstants.CODE_200);
        asynResult.setMsg(MqttUtil.successString);
        asynResult.setIdentity(panel.getId());
//        asynResult.setSymbol("data");
        asynResult.setContent(Collections.singleton(panelVO));
        asynResult.setTimestamp(System.currentTimeMillis());
        MqttUtil.send(PanelVO.TOPIC, asynResult);
        return "OK";
    }


    public void receiveDataForShandongreceive(String body) {
        try {
            NotifyDeviceDataChangedDTO dto;
            dto = JsonUtil.convertJsonStringToObject(body, NotifyDeviceDataChangedDTO.class);
            ObjectNode objectNode = dto.getService().getData();
            JsonNode msgNode = objectNode.get("DATA");
            String msgStr = msgNode.asText();
            Boolean checkResult = checkData(msgStr);
            if (!checkResult) {
                //数据验证失败
                return;
            }

            String[] msgArray = msgStr.split(",");
            //编号
            String serialNo = msgArray[0];
            serialNo = serialNo.substring(3);

            LogUtil.getLogAndInfo(serialNo, "NB", body);
            CommPanel panel = repositoryService.getCommPanelByNodeSerial(serialNo);
            if (null == panel) {
                log.info("nb面板不存在，编号为：{}", serialNo);
                return;
            }
            Date time = new Date();
            // 温度
            String tem = msgArray[1];
            tem = tem.substring(0, 3) + "." + tem.substring(3);

            BigDecimal temperature = new BigDecimal(tem);
            PanelVO panelVO = new PanelVO();
            panelVO.setSerial(serialNo);
//            panelVO.setTemperature(temperature.floatValue());
            panelVO.setPanelDate(time);
//            panelVO.setPlanTime(time);
            panelVO.setReadTime(time);
            panelVO.setTemperature(temperature.setScale(2, RoundingMode.HALF_UP).floatValue());
//            currentData.setState(true);
            AsynResult asynResult = new AsynResult();
            asynResult.setCode(ResultConstants.CODE_200);
            asynResult.setMsg(MqttUtil.successString);
            asynResult.setIdentity(panel.getId());
//            asynResult.setSymbol("data");
            asynResult.setContent(Collections.singleton(panelVO));
            asynResult.setTimestamp(System.currentTimeMillis());
            MqttUtil.send(PanelVO.TOPIC, asynResult);
        } catch (Exception e) {
            log.error("领图数据报错：", e);
        }
        log.info("领图数据处理成功");
    }

    public void handlelingTu2(String body) {
        log.info("接受到的领图2的数据：{}", body);
        try {
            NotifyDeviceDataChangedDTO dto = null;
            dto = JsonUtil.convertJsonStringToObject(body, NotifyDeviceDataChangedDTO.class);
            ObjectNode objectNode = dto.getService().getData();
            String msgStr = objectNode.toString();

            Map map = JSONObject.parseObject(msgStr, Map.class);
            BigDecimal temperature = null;
            Object tempObject = map.get("TEMP");
            if (tempObject != null) {
                BigDecimal tem = new BigDecimal(tempObject.toString());
                temperature = tem.subtract(threehundred).divide(ten, 2, BigDecimal.ROUND_HALF_UP);
            }
            String serialNo = (String) map.get("SN");
            LogUtil.getLogAndInfo(serialNo, "NB", body);
            CommPanel panel = repositoryService.getCommPanelByNodeSerial(serialNo);
            if (null == panel) {
                log.info("nb面板不存在，编号为：{}", serialNo);
                return;
            }
            Date time = new Date();
            PanelVO currentData = new PanelVO();
//            currentData.setTemperature(temperature.floatValue());
            currentData.setPanelDate(time);
//            currentData.setPlanTime(time);
            currentData.setReadTime(time);
            if (null != temperature) {
                currentData.setTemperature(temperature.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
            }
//            currentData.setState(true);
//            upService.upTemperaturePanelData(currentData);
            AsynResult asynResult = new AsynResult();
            asynResult.setCode(ResultConstants.CODE_200);
            asynResult.setMsg(MqttUtil.successString);
            asynResult.setIdentity(panel.getId());
//            asynResult.setSymbol("data");
            asynResult.setContent(Collections.singleton(currentData));
            asynResult.setTimestamp(System.currentTimeMillis());
            MqttUtil.send(PanelVO.TOPIC, asynResult);
        } catch (Exception e) {
            log.error("领图2数据报错：", e);
        }
        log.info("领图2数据处理成功");
    }

    /**
     * 判断接受数据是否满足格式
     * 判断采集数据格式是否正确，采集数据格式为长度52个字符，以*开头并且以#结尾，内容数据以","分隔，
     * 如：*ID867726030068979,+290,00,TEL8986031744206781891,1#
     */
    private boolean checkData(String msgStr) {
        char[] chars = msgStr.toCharArray();
        //验证长度
        if (chars.length != 52) {
            return false;
        }
        //验证*
        if (chars[0] != '*') {
            return false;
        }
        //验证ID
        if (chars[1] != 'I' || chars[2] != 'D') {
            return false;
        }
        return true;
    }

    @Resource
    private CommNbcmdRepository commNbcmdRepository;
    @Resource
    private CommNbCmdService commNbCmdService;
    @Resource
    private CommPanelRepository commPanelRepository;
    @Resource
    private CommTemperaturepressureRepository commTemperaturepressureRepository;
    @Resource
    private CommValveRepository commValveRepository;
    @Resource
    private CommMeterRepository commMeterRepository;
//    //保存电信信息ORM
//    private void insertORM(String serial, String tenantId, String productId, String deviceId, String deviceType, String nbPanelType) {
//        CommDxorm commDxorm = new CommDxorm();
//        commDxorm.setSerial(serial);
//        commDxorm.setTenantId(tenantId);
//        commDxorm.setProductId(productId);
//        commDxorm.setDeviceId(deviceId);
//        commDxorm.setDeviceType(deviceType);
//        commDxorm.setNbPanelType(nbPanelType);
//        commDxormRepository.save(commDxorm);
//    }

    private String queryDevice(NewReportDataBaseVo reportBaseDTO) {
        try {
            AepDeviceManagementClient client = getAepDeviceManagementClient();
            QueryDeviceRequest queryDeviceRequest = new QueryDeviceRequest();
            queryDeviceRequest.setParamDeviceId(reportBaseDTO.getDeviceId());
            queryDeviceRequest.setParamMasterKey(newMqttNbIotConfig.getRuiPanelMasterKey());
            queryDeviceRequest.setParamProductId(newMqttNbIotConfig.getRuiPanelProductId());
            QueryDeviceResponse device = client.QueryDevice(queryDeviceRequest);
            String s = new String(device.getBody());
//            log.info(JSON.toJSONString(s));
            JSONObject jsonObject = JSONObject.parseObject(s);
            Integer code = (Integer) jsonObject.get("code");
            if (code == 0) {
                JSONObject result = (JSONObject) jsonObject.get("result");
                return (String) result.get("deviceName");
            }
//            client.shutdown();
        } catch (Exception e) {
//
            log.error("查询电信device失败-----" + JSON.toJSONString(reportBaseDTO), e);
        }
        return null;
    }

    private void updateDevice(NewReportDataBaseVo reportBaseDTO) {
        try {
            AepDeviceManagementClient client = getAepDeviceManagementClient();
            UpdateDeviceRequest updateDeviceRequest = new UpdateDeviceRequest();
            updateDeviceRequest.setParamDeviceId(reportBaseDTO.getDeviceId());
            updateDeviceRequest.setParamMasterKey(newMqttNbIotConfig.getRuiPanelMasterKey());
            HashMap<String, Object> map = new HashMap<>();
            map.put("deviceName", reportBaseDTO.getPayload().getDevice_code());
            map.put("operator", "COMM");
            map.put("productId", reportBaseDTO.getProductId());
            byte[] bytes = JSONObject.toJSONString(map).getBytes();
            updateDeviceRequest.setBody(bytes);

            UpdateDeviceResponse updateDeviceResponse = client.UpdateDevice(updateDeviceRequest);
            String s = new String(updateDeviceResponse.getBody());
            JSONObject jsonObject = JSONObject.parseObject(s);
            Integer code = (Integer) jsonObject.get("code");
            if (code == 0) {
                log.info("更新电信device成功-----" + JSON.toJSONString(updateDeviceResponse));
            }
//            client.shutdown();
        } catch (Exception e) {

            log.error("更新电信device失败-----" + JSON.toJSONString(reportBaseDTO));
        }
//        return null;
//        return null;
    }

    public void receiveAEP_Panel(NewReportDataBaseVo reportBaseDTO) {
        NewMqttRuiPanelVo mqttPanelVo = reportBaseDTO.getPayload();
        if (null != mqttPanelVo) {
            //枣庄的小瑞面板，上行收到数据后，判断device_code和电信平台里面维护的档案的设备名称是否是一样的，如果不是，需要调用电信平台的api接口进行修改成一样的
            if (reportBaseDTO.getProductId().equalsIgnoreCase("15129532")) {
                String deviceName = queryDevice(reportBaseDTO);
                if (!deviceName.equalsIgnoreCase(reportBaseDTO.getPayload().getDevice_code())) {
                    updateDevice(reportBaseDTO);
                }
            }

            log.info("------nb-iot小瑞面板开始组合数据：{}", mqttPanelVo.getUp_data_interval().toString());
            Date now = new Date();
            List<String> temps = Arrays.asList(mqttPanelVo.getTemp().split(","));
            List<String> humiditys = Arrays.asList(mqttPanelVo.getHumidity().split(","));
            // 反向遍历
            Collections.reverse(temps);
            Collections.reverse(humiditys);
            PanelVO panelVO = new PanelVO();
            panelVO.setSerial(mqttPanelVo.getDevice_code());
            LogUtil.getLogAndInfo(mqttPanelVo.getDevice_code(), "NB", JSON.toJSONString(reportBaseDTO));
            CommPanel commPanel = commPanelRepository.findOne(Example.of(CommPanel.builder().serial(mqttPanelVo.getDevice_code()).communicationType(2)
                    .factoryName("瑞纳").build())).orElse(null);
            if (commPanel == null) {
                //枣庄，小瑞，如果没有档案，需要下行这个校时指令
                if (reportBaseDTO.getProductId().equalsIgnoreCase("15129532")) {
                    nbSendService.sendDownCommand(reportBaseDTO.getDeviceId(), reportBaseDTO.getProductId(), newMqttNbIotConfig.getAppKey()
                            , newMqttNbIotConfig.getAppSecret(), newMqttNbIotConfig.getRuiPanelMasterKey()
                            , getZaozhuangCmd());
                } else {
                    nbSendService.sendRtcCmd(reportBaseDTO.getDeviceId(), reportBaseDTO.getProductId(), newMqttNbIotConfig.getAppKey()
                           , newMqttNbIotConfig.getAppSecret(), newMqttNbIotConfig.getRuiPanelMasterKey());
                }
                log.error("数据库无数据---" + JSON.toJSONString(reportBaseDTO));
                return;
            }
            nbSendService.sendDxCmdOfXiaoRui(commPanel.getId(), reportBaseDTO);
//            panelVO.setTemperature(temperature.floatValue());
            panelVO.setPanelDate(now);
            panelVO.setReadTime(now);
            panelVO.setBatteryVol(Float.valueOf(mqttPanelVo.getBattery_level()));
//            panelVO.setPlanTime(time);
            panelVO.setSignal(String.valueOf(mqttPanelVo.getSignal_level()));
//            panelVO.setReadTime(new Date(mqttPanelVo.getUp_time() * 1000));
            panelVO.setSoftVersion(mqttPanelVo.getSoft_version());
//            panelVO.setTemperature(new BigDecimal(temps.get(0)).divide(BigDecimal.TEN, 2, RoundingMode.HALF_UP).floatValue());
            panelVO.setStatus(String.valueOf(mqttPanelVo.getErrcode()));
            panelVO.setWakeUpCycle(String.valueOf(mqttPanelVo.getUp_data_interval()));
//            panelVO.setHumidity(new BigDecimal(humiditys.get(0)).divide(BigDecimal.TEN, 2, RoundingMode.HALF_UP).floatValue());
//            panelVO.setNbType("1");
//            currentData.setState(true);
            Integer interval = mqttPanelVo.getSave_data_interval();
            ArrayList<PanelVO> panelVOS = new ArrayList<>();
            for (int i = 0; i < temps.size(); i++) {
                panelVO.setTemperature(new BigDecimal(temps.get(i)).divide(BigDecimal.TEN, 2, RoundingMode.HALF_UP).floatValue());
                panelVO.setHumidity(new BigDecimal(humiditys.get(i)).divide(BigDecimal.TEN, 2, RoundingMode.HALF_UP).floatValue());
                panelVO.setReadTime(DateUtils.addMinutes(now, -interval * i));
                panelVO.setPanelDate(DateUtils.addMinutes(now, -interval * i));
                panelVOS.add(panelVO);
            }
            AsynResult asynResult = new AsynResult();
            asynResult.setCode(ResultConstants.CODE_200);
            asynResult.setMsg(MqttUtil.successString);
//            asynResult.setSymbol("data");
//            if (mqttPanelVo.getUp_time() > 1699510427872L) {
//                asynResult.setTimestamp(mqttPanelVo.getUp_time());
//            } else {
//                asynResult.setTimestamp(mqttPanelVo.getUp_time() * 1000);
//            }
            asynResult.setTimestamp(System.currentTimeMillis());
            asynResult.setContent(panelVOS);
            asynResult.setIdentity(commPanel.getId());
            MqttUtil.send(PanelVO.TOPIC, asynResult);


        }
    }

    /*
     *
     */
    @Test
    public void test1() {
        System.out.println(System.currentTimeMillis());

    }

    public CommNbcmd getCommNbCmd(String id) {
        return commNbcmdRepository.findById(id).orElse(null);
    }

    public List<NBOrder> getNbOrders(CommNbcmd commNbcmd) {
        List<NBOrder> nbOrders = new ArrayList<>();
        if (commNbcmd != null && commNbcmd.getOrderSequence() != null && commNbcmd.getOrderSequence().length() > 5) {
            nbOrders = JSON.parseArray(commNbcmd.getOrderSequence(), NBOrder.class);
            //删除下发指令
            commNbcmd.setOrderSequence(null);
            commNbcmdRepository.save(commNbcmd);
        }
        return nbOrders;
    }

    private String getZaozhuangCmd() {
        net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
        jsonObject.put("up_data_interval", "240");
        jsonObject.put("save_data_interval", "15");
        jsonObject.put("lessee_code", "0");
        jsonObject.put("temp_offset", "0");
        jsonObject.put("humidity_offset", "0");
        jsonObject.put("updatetime", System.currentTimeMillis() / 1000 + "");
        return jsonObject.toString();
    }

    private String getDxCmdOfXiaoRui(NewReportDataBaseVo reportBaseDTO, NBOrder nbOrder) {
        net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
        addCheckTimeCmd(reportBaseDTO.getPayload().getSoft_version(), jsonObject);
        jsonObject.put("up_data_interval", reportBaseDTO.getPayload().getUp_data_interval().toString());
        jsonObject.put("save_data_interval", reportBaseDTO.getPayload().getSave_data_interval().toString());
        if (nbOrder != null && nbOrder.getWakeupCycle() != null) {
            addWakeUpCycleCmd(jsonObject, nbOrder.getWakeupCycle());
        }
        jsonObject.put("temp_offset", "0");
        if (nbOrder != null && nbOrder.getCompensation() != null) {
            addCompensationCommand(nbOrder.getCompensation(), jsonObject);
        }
        jsonObject.put("humidity_offset", reportBaseDTO.getPayload().getHumidity_offset().toString());
        jsonObject.put("lessee_code", reportBaseDTO.getPayload().getLessee_code().toString());
        return jsonObject.toString();
    }

    /**
     * 设备校时时间
     */
    public static void addCheckTimeCmd(String soft_version, net.sf.json.JSONObject jsonObject) {
        long now = System.currentTimeMillis();
        if ("V1.0.0".equals(soft_version)) {
            now = (now / 1000) + (24 * 60 * 60);
        } else {
            now = now / 1000;
        }
        jsonObject.put("updatetime", now + "");
    }

    /**
     * 下发唤醒周期
     */
    public static void addWakeUpCycleCmd(net.sf.json.JSONObject jsonObject, String wakeUpCycle) {
//            if (null != wakeUpCycle && checkCanSendWakeUpCycle(wakeUpCycleAddTime)) {
        if (null != wakeUpCycle) {
            jsonObject.put("up_data_interval", wakeUpCycle);
            jsonObject.put("save_data_interval", wakeUpCycle);
        }
    }

    /**
     * 检查唤醒周期是否超过 24小时30分钟
     * true:能发送  false:不能发送
     */
    public static boolean checkCanSendWakeUpCycle(Date addTime) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(addTime);
        calendar.add(Calendar.MINUTE, 1470);
        Date temp = calendar.getTime();
        return System.currentTimeMillis() <= temp.getTime();
    }

    private static void addCompensationCommand(String compensation, net.sf.json.JSONObject jsonObject) {
        //值1代表0.1  小瑞面板乘10 只取整数部分
        BigDecimal c = new BigDecimal(compensation).multiply(new BigDecimal(10));
        //只取整数部分
        jsonObject.put("temp_offset", c.intValue());
    }

    @Resource
    private MqttNbIotConfig mqttNbIotConfig;
    @Resource
    private NewMqttNbIotConfig newMqttNbIotConfig;
    @Resource
    private LKBMqttNbIotConfig lkbMqttNbIotConfig;

    private AepDeviceManagementClient client;

    private AepDeviceManagementClient getAepDeviceManagementClient() {
        if (client == null) {
            client = AepDeviceManagementClient.newClient().appKey(newMqttNbIotConfig.getAppKey()).appSecret(newMqttNbIotConfig.getAppSecret()).build();
        }
        return client;
    }

    /**
     * 先存储在数据库中，等待设备上线发送
     */
    public Result ToDxCmd(String identity, Integer wakeUpCycle, String compensation, BigDecimal sendOpening) {
        NBOrder nbOrder = new NBOrder();
        nbOrder.setWakeupCycle(String.valueOf(wakeUpCycle));
        nbOrder.setCompensation(compensation);
        nbOrder.setOpen(String.valueOf(sendOpening));
        commNbCmdService.addNbOrder(identity, nbOrder);
        return Result.success();
    }

    /**
     * 真正的发送
     */
    private void sendCmdReal(String deviceId, String productId, String APP_KEY, String APP_SECRET, String MASTER_KEY, String cmd, String host) {
        log.debug("deviceId:{} productId:{} APP_KEY:{} APP_SECRET:{} MASTER_KEY:{} host:{} 下发指令 {}", deviceId, productId, APP_KEY, APP_SECRET, MASTER_KEY, host, cmd);
        if (StringUtil.isNotBlank(host)) {
            AepDeviceCommandClient client = AepDeviceCommandClient.newClient().host(host)
                    .appKey(APP_KEY).appSecret(APP_SECRET)
                    .build();
            sendCmdReal(client, deviceId, productId, MASTER_KEY, cmd);
        } else {
            sendCmdReal(deviceId, productId, APP_KEY, APP_SECRET, MASTER_KEY, cmd);
        }
    }

    private void sendCmdReal(String deviceId, String productId, String APP_KEY, String APP_SECRET, String MASTER_KEY, String cmd) {
        AepDeviceCommandClient client = AepDeviceCommandClient.newClient()
                .appKey(APP_KEY).appSecret(APP_SECRET)
                .build();
        sendCmdReal(client, deviceId, productId, MASTER_KEY, cmd);
    }

    private void sendCmdReal(AepDeviceCommandClient client, String deviceId, String productId, String MASTER_KEY, String cmd) {
        SendCmdDetailVo sendCmdDetailVo = new SendCmdDetailVo();
        //代表字符串
        sendCmdDetailVo.setDataType(1);
        sendCmdDetailVo.setPayload(cmd);
        CreateCommandRequest request = new CreateCommandRequest();
        request.setParamMasterKey(MASTER_KEY);
        SendCmdBaseVo sendBaseVo = new SendCmdBaseVo();
        sendBaseVo.setDeviceId(deviceId);
        //operator: 操作者，必填
        sendBaseVo.setOperator("RUNA_COMM_NODE");
        sendBaseVo.setProductId(productId);
        //设备指令缓存时长，选填。单位：秒，取值范围：0-864000。 不携带则默认值：7200。如不需缓存请填0
        sendBaseVo.setTtl(7200);
        sendBaseVo.setContent(sendCmdDetailVo);
        String body = JSONObject.toJSONString(sendBaseVo);
        log.info("masterKey:{} productId:{} deviceId:{} 电信平台下发请求:{}", MASTER_KEY, productId, deviceId, body);
        request.setBody(body.getBytes());
        CreateCommandResponse commandResponse = null;
        try {
            commandResponse = client.CreateCommand(request);
        } catch (Exception e) {
            log.error("", e);
        }
        String responseMsg = new String(commandResponse.getBody(), StandardCharsets.UTF_8);
        log.info("masterKey:{} productId:{} deviceId:{} 电信平台返回结果:{}", MASTER_KEY, productId, deviceId, responseMsg);
        client.shutdown();
    }


    private String finalGen(List<SendCmdParamVo> sendCmdParamVoList, String sendContent) {
        if (!CollectionUtils.isEmpty(sendCmdParamVoList)) {
            for (SendCmdParamVo sendCmdParamVo : sendCmdParamVoList) {
                if (StringUtils.isBlank(sendContent)) {
                    sendContent = sendCmdParamVo.getParamKey() + sendCmdParamVo.getParamValue();
                } else {
                    sendContent = sendContent + "," + sendCmdParamVo.getParamKey() + sendCmdParamVo.getParamValue();
                }
            }
        }
        return sendContent;
    }


    @SneakyThrows
    public void receiveAEP_RU_Temperature(ReportDataBaseVo baseVo) {
        ReportDataDetailVo reportDataDetailVo = baseVo.getPayload();
        if (null != reportDataDetailVo && StringUtils.isNotBlank(reportDataDetailVo.getAPPdata())) {
            String decodeContent = new String(Base64Utils.decodeFromString(reportDataDetailVo.getAPPdata()));
            log.info("------nb-iot-ru温度面板，上传数据解码后的内容为：" + decodeContent + "------getDeviceId: " + baseVo.getDeviceId());
            //解析参数
            Map<String, String> paramMap = MqttSetUtils.getParsingArgumentsMap(decodeContent);
            //温度面板编号
            String serialNo = paramMap.get("id");
            LogUtil.getLogAndInfo(serialNo, "NB", JSON.toJSONString(baseVo));
            CommPanel commPanel = null;
            boolean validate = true;
            //设备厂家
            commPanel = commPanelRepository.findOne(Example.of(CommPanel.builder().serial(serialNo).communicationType(2)
                    .factoryName("瑞纳").build())).orElse(null);
            if (commPanel == null) {
                log.error("数据库无数据---" + JSON.toJSONString(baseVo));
                validate = false;
            }
            if (!validate) {
                nbSendService.sendRtcCmd(baseVo.getDeviceId(), baseVo.getProductId(), mqttNbIotConfig.getAppKey()
                        , mqttNbIotConfig.getAppSecret(), mqttNbIotConfig.getRuPanelMasterKey(), mqttNbIotConfig.getHost());
                return;
            }
            nbSendService.sendCmdReal(commPanel.getId(), baseVo, paramMap.get("hot"), paramMap.get("uitv1"), paramMap.get("uitv2"));

            //采集时间
            Date planTime = UtilTime.StringToDate(paramMap.get("rtc"), "yyyyMMddHHmmss");
            //采集的温度
            String tempStr = null;
            String humidityStr = null;
            String supplyTemperatureStr = MqttTemperaturePressureUtils.filterStr(paramMap.get("T1"));//供温
            String[] supplyTemperatureArray = StringUtils.isEmpty(supplyTemperatureStr) ? new String[]{} : supplyTemperatureStr.split("_");
            String supplyHumidityStr = MqttTemperaturePressureUtils.filterStr(paramMap.get("RH"));//湿度
            String[] supplyHumidityArray = StringUtils.isEmpty(supplyHumidityStr) ? new String[]{} : supplyHumidityStr.split("_");
//            if (supplyTemperatureArray.length != 0) {
//                tempStr = supplyTemperatureArray[supplyTemperatureArray.length - 1];
//            }
            BigDecimal temperature = null;
//            if (StringUtils.isNotBlank(tempStr)) {
//                temperature = new BigDecimal(tempStr).setScale(2, RoundingMode.HALF_UP);
//            }
//            if (supplyHumidityArray.length != 0) {
//                humidityStr = supplyHumidityArray[supplyHumidityArray.length - 1];
//            }
            BigDecimal humidity = null;
//            if (StringUtils.isNotBlank(humidityStr)) {
//                humidity = new BigDecimal(humidityStr).setScale(2, RoundingMode.HALF_UP);
//            }
            //信号强度
            String csqStr = paramMap.get("csq");
            BigDecimal csq = null;
            if (StringUtils.isNotBlank(csqStr)) {
                csq = new BigDecimal(csqStr).setScale(2, RoundingMode.HALF_UP);
            }
            //通讯质量
            String rsrpStr = paramMap.get("rsrp");
            BigDecimal rsrp = null;
            if (StringUtils.isNotBlank(rsrpStr)) {
                rsrp = new BigDecimal(rsrpStr).setScale(2, RoundingMode.HALF_UP);
            }
            //构造数据
            PanelVO panelVO = new PanelVO();
            if (!StringUtils.isEmpty(paramMap.get("Tc")))
                panelVO.setTc(paramMap.get("Tc"));
            //状态字
            String stateCode = paramMap.get("sta");
            String period;
            String acquisitionCycle;
            //判断是否是供暖季
            String hot = paramMap.get("hot");
            if (DateUtil.heatingPeriod(hot)) {
                period = paramMap.get("uitv1");
                acquisitionCycle = paramMap.get("sitv1");
            } else {
                period = paramMap.get("uitv2");
                acquisitionCycle = paramMap.get("sitv2");
            }

            paramMap.get("uitv2");
            String eco = paramMap.get("bat");
            log.info("ru面板解析后的eco =" + eco);
            //00:正常  80：面板分离
            if ("80".equals(stateCode)) {
                panelVO.setFaultCode(MqttSetUtils.MBCX);
            }
            panelVO.setSerial(serialNo);
//            panelVO.setFactoryName(factoryName);
            //            panelVO.setPlanTime(planTime);
            panelVO.setSignal(String.valueOf(csq));
            panelVO.setRsrp(String.valueOf(rsrp));
            panelVO.setWakeUpCycle(period);
//            mqttPanelVo.setCommunicationType(COMMUNICATION_NB_LOT);
            panelVO.setStatus(stateCode);

//            panelVO.setReadTime(planTime);
//            panelVO.setPanelDate(planTime);
            panelVO.setBatteryVol(Float.valueOf(eco));
//            panelVO.setHumidity(humidity);
            ArrayList<PanelVO> panelVOS = new ArrayList<>();
            int integerOfAcquisitionCycle = Integer.parseInt(acquisitionCycle);
            for (int i = 0; i < supplyTemperatureArray.length; i++) {
                panelVO.setTemperature(new BigDecimal(supplyTemperatureArray[i]).setScale(2, RoundingMode.HALF_UP).floatValue());
                if (supplyHumidityArray.length > i) {
                    panelVO.setHumidity(new BigDecimal(supplyHumidityArray[i]).setScale(2, RoundingMode.HALF_UP).floatValue());
                }
                panelVO.setReadTime(DateUtils.addMinutes(planTime, -integerOfAcquisitionCycle * i));
                panelVO.setPanelDate(DateUtils.addMinutes(planTime, -integerOfAcquisitionCycle * i));
                panelVOS.add(panelVO);
            }
//            mqttPanelVo.setEco(eco);
//            mqttRuPanelCalService.handleBusinessTemperaturePanelData(mqttPanelVo, sendCmdConfigVo);
            AsynResult asynResult = new AsynResult();
            asynResult.setCode(ResultConstants.CODE_200);
            asynResult.setMsg(MqttUtil.successString);
//            asynResult.setSymbol("data");
//            asynResult.setTimestamp(planTime.getTime());
            asynResult.setContent(panelVOS);
            asynResult.setIdentity(commPanel.getId());
            LogUtil.getLogAndInfo(serialNo, "NB", "上报: {}", JSON.toJSONString(asynResult));
            MqttUtil.send(PanelVO.TOPIC, asynResult);
        }

    }

    public void receiveAEP_Temperature(ReportDataBaseVo baseVo, String platform) {
        ReportDataDetailVo reportDataDetailVo = baseVo.getPayload();
        if (null != reportDataDetailVo && StringUtils.isNotBlank(reportDataDetailVo.getAPPdata())) {
            String decodeContent = new String(Base64Utils.decodeFromString(reportDataDetailVo.getAPPdata()));
            log.info("------nb-iot温度面板，上传数据解码后的内容为：" + decodeContent + "------getDeviceId: " + baseVo.getDeviceId());
            if ("RUNA".equals(platform)) {
                //解析参数
                Map<String, String> paramMap = MqttSetUtils.getParsingArgumentsMap(decodeContent);
                //温度面板编号
                String serialNo = paramMap.get("id");
                LogUtil.getLogAndInfo(serialNo, "NB", JSON.toJSONString(baseVo));
                CommPanel commPanel = null;
                boolean validate = true;
                commPanel = commPanelRepository.findOne(Example.of(CommPanel.builder().serial(serialNo).communicationType(2)
                        .factoryName("瑞纳").build())).orElse(null);
                if (commPanel == null) {
                    log.error("数据库无数据---" + JSON.toJSONString(baseVo));
                    validate = false;
                }
                if (!validate) {
                    nbSendService.sendRtcCmd(baseVo.getDeviceId(), baseVo.getProductId(), mqttNbIotConfig.getAppKey()
                            , mqttNbIotConfig.getAppSecret(), mqttNbIotConfig.getPanelMasterKey());
                    return;
                }
                nbSendService.sendCmdToRunaTemperature(commPanel.getId(), baseVo, paramMap.get("period"));

                //采集时间
                Date planTime = UtilTime.StringToDate(paramMap.get("rtc"), "yyyyMMddHHmmss");
                //采集的温度
                String tempStr = paramMap.get("temp");
                BigDecimal temperature = null;
                if (StringUtils.isNotBlank(tempStr)) {
                    temperature = new BigDecimal(tempStr).setScale(2, RoundingMode.HALF_UP);
                }
                //信号强度
                String csqStr = paramMap.get("csq");
                BigDecimal csq = null;
                if (StringUtils.isNotBlank(csqStr)) {
                    csq = new BigDecimal(csqStr).setScale(2, RoundingMode.HALF_UP);
                }
                //通讯质量
                String rsrpStr = paramMap.get("rsrp");
                BigDecimal rsrp = null;
                if (StringUtils.isNotBlank(rsrpStr)) {
                    rsrp = new BigDecimal(rsrpStr).setScale(2, RoundingMode.HALF_UP);
                }
                //构造数据
                PanelVO panelVO = new PanelVO();
                //状态字
                String stateCode = paramMap.get("sta");
                String period = paramMap.get("period");
                //00:正常  80：面板分离
                if ("80".equals(stateCode)) {
                    panelVO.setFaultCode(MqttSetUtils.MBCX);
                }
                panelVO.setSerial(serialNo);
//            panelVO.setFactoryName(factoryName);
                if (temperature != null) {
                    panelVO.setTemperature(temperature.floatValue());
                }
//            panelVO.setPlanTime(planTime);
                panelVO.setSignal(String.valueOf(csq));
                panelVO.setRsrp(String.valueOf(rsrp));
//            mqttPanelVo.setRsrp(rsrp);
//            if (humidity != null) {
//                panelVO.setHumidity(humidity.floatValue());
//            }
                panelVO.setReadTime(new Date());
                panelVO.setPanelDate(new Date());
                panelVO.setWakeUpCycle(period);
//            mqttPanelVo.setCommunicationType(COMMUNICATION_NB_LOT);
                panelVO.setStatus(stateCode);
//            mqttPanelVo.setEco(eco);
//            mqttRuPanelCalService.handleBusinessTemperaturePanelData(mqttPanelVo, sendCmdConfigVo);
                AsynResult asynResult = new AsynResult();
                asynResult.setCode(ResultConstants.CODE_200);
                asynResult.setMsg(MqttUtil.successString);
//            asynResult.setSymbol("data");
                asynResult.setTimestamp(planTime.getTime());
                asynResult.setContent(Collections.singleton(panelVO));
                asynResult.setIdentity(commPanel.getId());
                MqttUtil.send(PanelVO.TOPIC, asynResult);
            } else if ("HDRX".equals(platform)) {
                String data = ByteUtil.byteToHexString(Base64Utils.decodeFromString(reportDataDetailVo.getAPPdata()));
                CommPanel commPanel = commPanelRepository.findOne(Example
                                .of(CommPanel.builder().serial(baseVo.getIMEI())
                                .communicationType(2).build())).orElse(null);
                if (commPanel != null) {
                    int csq = Integer.parseInt(data.substring(28, 30), 16);
                    PanelVO panelVO;
                    AsynResult asynResult = new AsynResult();
                    int index = 102;
                    int num = Integer.parseInt(data.substring(index, 104), 16);
                    index += 2;
                    List<PanelVO> panelVOS = new ArrayList<>();
                    for (int i = 0; i < num; i++) {
                        panelVO = new PanelVO();
                        panelVO.setSignal(String.valueOf(csq));
                        panelVO.setPanelDate(new Date(Integer.parseInt(data.substring(index, index + 8), 16) * 1000L));
                        index += 8;
                        panelVO.setTemperature((float) (Integer.parseInt(data.substring(index, index + 4), 16) * 0.01));
                        index += 4;
                        panelVO.setHumidity((float) (Integer.parseInt(data.substring(index, index + 4), 16) * 0.01));
                        index += 4;
                        panelVOS.add(panelVO);
                    }
                    asynResult.setIdentity(commPanel.getId());
                    asynResult.setCode(ResultConstants.CODE_200);
                    asynResult.setMsg(MqttUtil.successString);
                    asynResult.setTimestamp(System.currentTimeMillis());
                    asynResult.setContent(panelVOS);
                    MqttUtil.send(PanelVO.TOPIC, asynResult);
                }
            }
        }
    }

    public void receiveAEP_LKB_Temperature(DataReportDTO baseVo) {
        String code = baseVo.getPayload().getServiceData().getTH();
        String imei = baseVo.getImei();
        String serialNo = imei.substring(imei.length() - 8);
        Map<Integer, Object> temMap = LKBMqttPanelUtils.deviceDataDecode(code);
        CommPanel commPanel = null;
        boolean validate = true;
        if (StringUtils.isBlank(serialNo)) {
            log.info("------琅卡博仪表编号不存在------");
            validate = false;
        } else {
            LogUtil.getLogAndInfo(serialNo, "NB", JSON.toJSONString(baseVo));
            commPanel = commPanelRepository.findOne(Example.of(CommPanel.builder().serial(serialNo).communicationType(2)
                    .build())).orElse(null);
            if (commPanel == null) {
                log.error("数据库无数据---" + JSON.toJSONString(baseVo));
                validate = false;
            }
        }

        if (!validate) {
            nbSendService.sendRtcCmd(baseVo.getDeviceId(), baseVo.getProductId(), lkbMqttNbIotConfig.getAppKey()
                    , lkbMqttNbIotConfig.getAppSecret(), lkbMqttNbIotConfig.getPanelMasterKey());
            return;
        }
        nbSendService.sendCmdToLkbTemperature(commPanel.getId(), baseVo);

        int b = 7;
        BigDecimal eight = (BigDecimal) temMap.get(8);
        BigDecimal temTwo = (BigDecimal) temMap.get(16);
        if (eight.compareTo(BigDecimal.ZERO) == 0) {
            b = 7;
        } else if (eight.compareTo(BigDecimal.ZERO) > 0 && temTwo.compareTo(BigDecimal.ZERO) == 0) {
            b = 15;
        } else if (temTwo.compareTo(BigDecimal.ZERO) > 0) {
            b = 23;
        }
        log.info("-----LKB本次更新至" + b + "点数据");

        //采集的温度
        BigDecimal temperature = (BigDecimal) temMap.get(b);
        if (temperature != null) {
            temperature = temperature.setScale(2, RoundingMode.HALF_UP);
        }
        //信号强度
        BigDecimal csqStr = temMap.get(24) == null ? null : (BigDecimal) temMap.get(24);
        Date time = temMap.get(26) == null ? null : (Date) temMap.get(26);
        if (csqStr != null) {
            csqStr = csqStr.setScale(2, RoundingMode.HALF_UP);
        }
        PanelVO panelVO = new PanelVO();
//        MqttPanelVo mqttPanelVo = new MqttPanelVo();
        AsynResult asynResult = new AsynResult();
        asynResult.setCode(ResultConstants.CODE_200);
        asynResult.setMsg(MqttUtil.successString);
//        asynResult.setSymbol("data");
        if (time != null) {
            String timeStr = UtilTime.dateToString(time, "yyyy-MM-dd" + " 00:00:00");
            Date dayTime = UtilTime.StringToDate(timeStr, "yyyy-MM-dd HH:mm:ss");
            Date planTime = UtilTime.addMinute(dayTime, b * 60);
//            mqttPanelVo.setPlanTime(planTime);
//            asynResult.setTimestamp(planTime.getTime());
            panelVO.setReadTime(new Date());
            panelVO.setPanelDate(planTime);
        }
        //构造数据
        panelVO.setSerial(serialNo);
//        mqttPanelVo.setFactoryName("中润");
        if (temperature != null) {
            panelVO.setTemperature(temperature.floatValue());
        }
        panelVO.setSignal(String.valueOf(csqStr));
//        mqttPanelVo.setCommunicationType(COMMUNICATION_NB_LOT);
//        mqttPanelCalService.handleBusinessTemperaturePanelData(mqttPanelVo, sendCmdConfigVo);
        asynResult.setContent(Collections.singleton(panelVO));
        asynResult.setIdentity(commPanel.getId());
        MqttUtil.send(PanelVO.TOPIC, asynResult);
    }

    /**
     * 获取下发指令内容
     *
     * @param sendCmdParamVoList 下发指令参数
     * @return 下发指令内容
     */
    public static String getSendCmdByParamList(List<SendCmdParamVo> sendCmdParamVoList) {
        String sendContent = null;
        if (!CollectionUtils.isEmpty(sendCmdParamVoList)) {
            for (SendCmdParamVo sendCmdParamVo : sendCmdParamVoList) {
                if (StringUtils.isBlank(sendContent)) {
                    sendContent = sendCmdParamVo.getParamKey() + sendCmdParamVo.getParamValue();
                } else {
                    sendContent = sendContent + "," + sendCmdParamVo.getParamKey() + sendCmdParamVo.getParamValue();
                }
            }
        }
        return sendContent;
    }


//    /*
//     *
//     */
//    @Test
//    public void test(){
//        String s="{\"upPacketSN\":-1,\"upDataSN\":-1,\"topic\":\"v1/up/ad\",\"timestamp\":1697182463562,\"tenantId\":\"2000039707\",\"serviceId\":\"\",\"protocol\":\"lwm2m\",\"productId\":\"15094169\",\"payload\":{\"APPdata\":\"ZnVuYzp1cCxyc3JwOjg4LHNucjo0LGFjdDowLHR5cDoxLGlkOjk3NDMyNzM0LGljYzo4OTg2MDRCODEwMjJDMDAxMjI2MCxjc3E6MTksc2V0OjgwLGN1cjo4MCxyY250OjMsc3RhOjE2Mzg0LHBhcjowLHZlcjoxMDEwLG1vZGU6MSx0YWM6MCxydGM6MjAyMzEwMTMxNTM0MjEsY2l0djE6NjAsdWl0djE6NjAsY2l0djI6MjE2MDAsdWl0djI6MjE2MDAsaG90OjEwMDEwNDAxLGJhdDozLjUsbGlmZToyMTYyNDYsZGxrOjUsYWNsczoxLGFjbHQ6NDMzMDAsYmxvY2s6MCxyZXA6MTAwLG1vdG1zOjI0NyxvbGRzOkJFLGZlY29kZToxMjg=\"},\"messageType\":\"dataReport\",\"deviceType\":\"\",\"deviceId\":\"bb80bf3ba5af4c6db1a3642093c0687d\",\"assocAssetId\":\"\",\"IMSI\":\"undefined\",\"IMEI\":\"861178067432734\"}";
//        ReportDataBaseVo reportDataBaseVo = JSON.parseObject(s, ReportDataBaseVo.class);
//        receiveAEP_BuildValve(reportDataBaseVo);
//    }

    public void receiveAEP_BuildValve(ReportDataBaseVo baseVo) {
        ReportDataDetailVo reportDataDetailVo = baseVo.getPayload();
        Long timestamp = baseVo.getTimestamp();
        if (null != reportDataDetailVo && StringUtils.isNotBlank(reportDataDetailVo.getAPPdata())) {
            String decodeContent = new String(Base64Utils.decodeFromString(reportDataDetailVo.getAPPdata()));
            log.info("------nb-iot楼阀，上传数据解码后的内容为：" + decodeContent + "------getDeviceId: " + baseVo.getDeviceId());
            Map<String, String> paramMap = MqttSetUtils.getParsingArgumentsMap(decodeContent);
            //编号
            String serialNo = paramMap.get("id");
            LogUtil.getLogAndInfo(serialNo, "NB", JSON.toJSONString(baseVo));
//            String typ = paramMap.get("typ");
//            boolean validate = true;
            CommValve commValve = commValveRepository.findOne(Example.of(CommValve.builder().serial(serialNo).communicationType(2)
                    .build())).orElse(null);
            if (commValve == null) {
                log.error("数据库无数据---" + JSON.toJSONString(baseVo));
                nbSendService.sendRtcCmd(baseVo.getDeviceId(), baseVo.getProductId(), mqttNbIotConfig.getAppKey()
                        , mqttNbIotConfig.getAppSecret(), mqttNbIotConfig.getBuildValveMasterKey(baseVo.getProductId()));
                return;
            }
            nbSendService.sendCmdToValve(commValve.getId(), baseVo, paramMap.get("uitv1"));

            // 校时时间
            Date date = new Date();
            String supplyTemStr = MqttBuildValveUtils.filterStr(paramMap.get("t1"));
            String[] supplyTemArray = null;
            if (StringUtils.isNotBlank(supplyTemStr)) {
                supplyTemArray = supplyTemStr.split(ARRAY_SPLIT);
            }
            String returnTemStr = MqttBuildValveUtils.filterStr(paramMap.get("t2"));
            String[] returnTemArray = null;
            if (StringUtils.isNotBlank(returnTemStr)) {
                returnTemArray = returnTemStr.split(ARRAY_SPLIT);
            }

            String supplyPreStr = MqttBuildValveUtils.filterStr(paramMap.get("p1"));
            String[] supplyPreArray = null;
            if (StringUtils.isNotBlank(supplyPreStr)) {
                supplyPreArray = supplyPreStr.split(ARRAY_SPLIT);
            }

            String returnPreStr = MqttBuildValveUtils.filterStr(paramMap.get("p2"));
            String[] returnPreArray = null;
            if (StringUtils.isNotBlank(returnPreStr)) {
                returnPreArray = returnPreStr.split(ARRAY_SPLIT);
            }

            BigDecimal actualOpening = null;
            String cur = paramMap.get("cur");
            if (null != cur) {
                actualOpening = stringToBigDecimal(cur);
            }

            BigDecimal controlOpening = null;
            String set = paramMap.get("set");
            if (null != set) {
                controlOpening = stringToBigDecimal(set);
            }

            BigDecimal batteryVolt = null;
            String bat = paramMap.get("bat");
            if (null != bat) {
                batteryVolt = stringToBigDecimal(bat, 3);
            }

            String stateCode = paramMap.get("sta");
            Integer powerType = null;
            Integer intSC = null;
            if (StringUtil.isNotBlank(stateCode)) {
                intSC = Integer.parseInt(stateCode, 16);
                powerType = intSC & 1;
            }

            //本地还是远程
            String controlModel = null;
            String model = paramMap.get("mode");
            if (StringUtil.isNotBlank(model)) {
                if ("1".equals(model)) {
                    controlModel = "远程";
                } else if ("0".equals(model)) {
                    controlModel = "本地";
                }
            }

            // String powerTime = paramMap.get("life");
            String version = paramMap.get("ver");
            String sign = paramMap.get("csq");
            String rsrp = paramMap.get("rsrp");
            //采样周期
            String citv = paramMap.get("uitv1");
            int sampling = StringUtil.isNotBlank(citv) ? Integer.parseInt(citv) : 0;
            if (null != supplyTemArray) {
                int length = supplyTemArray.length;
                for (int i = 0; i < length; i++) {
                    ValveVO valveVO = new ValveVO();
                    valveVO.setValveSerial(serialNo);
                    if (actualOpening != null) {
                        valveVO.setActOpen(actualOpening.floatValue());
                        valveVO.setRemoteSet(controlOpening.floatValue());
                    }
//                valveVO.setReadTime(UtilTime.addMinute(checkTime, -sampling * (length - i - 1)));
//                valveVO.setValveDate(UtilTime.addMinute(checkTime, -sampling * (length - i - 1)));
                    valveVO.setReadTime(UtilTime.addMinute(date, -sampling * (length - i - 1)));
                    valveVO.setValveDate(UtilTime.addMinute(date, -sampling * (length - i - 1)));
//                valveVO.setActualValue(actualOpening);
//                valveVO.setTargetValue(controlOpening);
                    valveVO.setSupplyTemp(stringToBigDecimal(supplyTemArray[i]).floatValue());
                    valveVO.setReturnTemp(stringToBigDecimal(returnTemArray[i]).floatValue());
                    valveVO.setStatus(stateCode);
                    valveVO.setLR(ValveVO.LREnum.valueOf(controlModel));
                    if (null != intSC) {
                        valveVO.setFaultCode(FaultUtil.runaDeviceBuildValveFaults(intSC, commValve.getModel()));
                    }
                    valveVO.setSignal(sign);
                    valveVO.setWakeUpCycle(citv);
                    valveVO.setRsrp(rsrp);
                    valveVO.setPowerType(powerType);
//                dataVo.setControlModel(controlModel);
                    valveVO.setBatteryVol(batteryVolt.floatValue());
//                valveVO.setPowerType(powerType);
                    valveVO.setSoftVersion(version);
//                dataList.add(dataVo);
                    if (null != supplyPreArray && supplyPreArray.length > 0 && i == 0) {
                        valveVO.setSupplyPre(stringToBigDecimal(supplyPreArray[0], 2).floatValue());
                    }
                    if (null != returnPreArray && returnPreArray.length > 0 && i == 0) {
                        valveVO.setReturnPre(stringToBigDecimal(returnPreArray[0], 2).floatValue());
                    }
                    AsynResult asynResult = new AsynResult();
                    asynResult.setCode(ResultConstants.CODE_200);
                    asynResult.setMsg(MqttUtil.successString);
//                asynResult.setSymbol("data");
                    asynResult.setTimestamp(UtilTime.addMinute(new Date(timestamp), -sampling * (length - i - 1)).getTime());
                    asynResult.setContent(valveVO);
                    asynResult.setIdentity(commValve.getId());
                    MqttUtil.send(ValveVO.TOPIC, asynResult);

                }
            } else {
                ValveVO valveVO = new ValveVO();
                valveVO.setValveSerial(serialNo);
                valveVO.setReadTime(date);
                valveVO.setValveDate(date);
                if (actualOpening != null) {
                    valveVO.setActOpen(actualOpening.floatValue());
                }
                if (null != controlOpening) {
                    valveVO.setRemoteSet(controlOpening.floatValue());
                }
                valveVO.setStatus(stateCode);
                if (null != controlModel) {
                    valveVO.setLR(ValveVO.LREnum.valueOf(controlModel));
                }
                if (null != intSC) {
                    valveVO.setFaultCode(FaultUtil.runaDeviceBuildValveFaults(intSC, commValve.getModel()));
                }
                valveVO.setSignal(sign);
                valveVO.setWakeUpCycle(citv);
                valveVO.setRsrp(rsrp);
                valveVO.setPowerType(powerType);
                if (null != batteryVolt) {
                    valveVO.setBatteryVol(batteryVolt.floatValue());
                }
                valveVO.setPowerType(powerType);
                valveVO.setSoftVersion(version);
                AsynResult asynResult = new AsynResult();
                asynResult.setCode(ResultConstants.CODE_200);
                asynResult.setMsg(MqttUtil.successString);
                asynResult.setTimestamp(timestamp);
                asynResult.setContent(valveVO);
                asynResult.setIdentity(commValve.getId());
                MqttUtil.send(ValveVO.TOPIC, asynResult);
            }

        }
    }


    /**
     * 数组分割符
     */
    private static final String ARRAY_SPLIT = "_";

    public void receiveAEP_Temperaturepressure(ReportDataBaseVo baseVo) {
        ReportDataDetailVo reportDataDetailVo = baseVo.getPayload();
        if (null != reportDataDetailVo && StringUtils.isNotBlank(reportDataDetailVo.getAPPdata())) {
            String decodeContent = new String(Base64Utils.decodeFromString(reportDataDetailVo.getAPPdata()));
            log.info("------nb-iot温压监测仪，上传数据解码后的内容为：" + decodeContent + "------getDeviceId: " + baseVo.getDeviceId());
            Map<String, String> paramMap = MqttSetUtils.getParsingArgumentsMap(decodeContent);
            //编号
            String serialNo = paramMap.get("id");
            LogUtil.getLogAndInfo(serialNo, "NB", JSON.toJSONString(baseVo));
            boolean validate = true;
            CommTemperaturepressure commTemperaturepressure = null;
            //设备厂家
            String type = paramMap.get("type");
            type = type == null ? paramMap.get("typ") : type;
            String factoryName = MqttSetUtils.getTemperaturePressureFactoryNameByType(type);
            if (StringUtils.isBlank(serialNo) || StringUtils.isBlank(factoryName)) {
                log.info("------nb-iot温压监测仪厂家或仪表编号不存在------");
                validate = false;
            } else {
                commTemperaturepressure = commTemperaturepressureRepository.findOne(Example.of(CommTemperaturepressure.builder().serial(serialNo)
                        .build())).orElse(null);
                if (commTemperaturepressure == null) {
                    log.error("数据库无数据---" + JSON.toJSONString(baseVo));
                    validate = false;
                }
            }

            if (!validate) {
                nbSendService.sendRtcCmd(baseVo.getDeviceId(), baseVo.getProductId(), mqttNbIotConfig.getAppKey()
                        , mqttNbIotConfig.getAppSecret(), mqttNbIotConfig.getTemperaturePressureMasterKey());
                return;
            }
            nbSendService.sendCmdToTemperaturePressure(commTemperaturepressure.getId(), baseVo, serialNo, paramMap.get("sta"), paramMap.get("uitv"));

            //校时时间
            Date checkTime = UtilTime.StringToDate(paramMap.get("rtc"), "yyyyMMddHHmmss");
            List<TemperaturePressureDataVo> dataList = new ArrayList<>();
            String supplyTemperatureStr = MqttTemperaturePressureUtils.filterStr(paramMap.get("T1"));//供温
            String returnTemperatureStr = MqttTemperaturePressureUtils.filterStr(paramMap.get("T2"));//回温
            String[] supplyTemperatureArray = StringUtils.isEmpty(supplyTemperatureStr) ? new String[]{} : supplyTemperatureStr.split(ARRAY_SPLIT);
            String[] returnTemperatureArray = StringUtils.isEmpty(returnTemperatureStr) ? new String[]{} : returnTemperatureStr.split(ARRAY_SPLIT);
            String supplyPressureStr = MqttTemperaturePressureUtils.filterStr(paramMap.get("P1"));//供压
            String returnPressureStr = MqttTemperaturePressureUtils.filterStr(paramMap.get("P2"));//回压
            String[] supplyPressureArray = StringUtils.isEmpty(supplyPressureStr) ? new String[]{} : supplyPressureStr.split(ARRAY_SPLIT);
            String[] returnPressureArray = StringUtils.isEmpty(returnPressureStr) ? new String[]{} : returnPressureStr.split(ARRAY_SPLIT);
            String batteryPressureStr = MqttTemperaturePressureUtils.filterStr(paramMap.get("bat"));//电池电压，电压阈值/单位mV（供电电压_电压阈值）
            String[] batteryPressureArray = StringUtils.isEmpty(batteryPressureStr) ? new String[]{} : batteryPressureStr.split(ARRAY_SPLIT);
            BigDecimal batteryPressure = null;
            if (batteryPressureArray.length > 0) {
                batteryPressure = stringToBigDecimal(batteryPressureArray[0]);
            }

            String temperatureCorrectionStr = MqttTemperaturePressureUtils.filterStr(paramMap.get("Tc"));//温度修正，_左侧修正T1，_右侧修正T2
//            String[] temperatureCorrectionArray = StringUtils.isEmpty(temperatureCorrectionStr) ? new String[]{} : temperatureCorrectionStr.split(ARRAY_SPLIT);
//            BigDecimal temperatureCorrection = null;
//            if (temperatureCorrectionArray.length > 0) {
//                temperatureCorrection = stringToBigDecimal(temperatureCorrectionArray[0]);
//            }
            String sign = paramMap.get("csq");
            String rsrp = paramMap.get("rsrp");
            //状态字位对应
            String stateCode = paramMap.get("sta");// 转成十进制
            String samplingStr = MqttTemperaturePressureUtils.filterStr(paramMap.get("citv"));//电池电压，电压阈值/单位mV（供电电压_电压阈值）
            String[] samplingArray = StringUtils.isEmpty(samplingStr) ? new String[]{} : samplingStr.split(ARRAY_SPLIT);
            BigDecimal sampling = null;
            if (samplingArray.length > 0) {
                sampling = stringToBigDecimal(samplingArray[0]);
            }
            String faultMsg = MqttTemperaturePressureUtils.getFaultMsgByCode(stateCode);
            int length = supplyTemperatureArray.length;
            for (int i = 0; i < length; i++) {
                TemperaturePressureCurrentData currentData = new TemperaturePressureCurrentData();
//                TemperaturePressureDataVo dataVo = new TemperaturePressureDataVo();
                currentData.setSerial(serialNo);
                currentData.setRsrp(rsrp);
//            mqttTemperaturePressureVo.setFactoryName(factoryName);
//                currentData.setStatus(stateCode + "");
                currentData.setFaultCode(faultMsg);
                Date planTime = UtilTime.addMinute(checkTime, -sampling.intValue() * (length - i - 1));
//                dataVo.setPlanTime(UtilTime.addMinute(checkTime, -sampling.intValue() * (length - i - 1)));
                if (supplyTemperatureArray.length > 0) {
                    currentData.setSupplyTemp(new BigDecimal(supplyTemperatureArray[i]).divide(new BigDecimal(10)).setScale(1, RoundingMode.HALF_UP).floatValue());
                }
                if (returnTemperatureArray.length > 0) {
                    currentData.setReturnTemp(new BigDecimal(returnTemperatureArray[i]).divide(new BigDecimal(10)).setScale(1, RoundingMode.HALF_UP).floatValue());
                }
                if (supplyPressureArray.length > 0) {
                    currentData.setSupplyPre(stringToBigDecimal(supplyPressureArray[i]).floatValue());
                }
                if (returnPressureArray.length > 0) {
                    currentData.setReturnPre(stringToBigDecimal(returnPressureArray[i]).floatValue());
                }
//                if (temperatureCorrection != null ) {
                currentData.setReturnTc(temperatureCorrectionStr.split("_")[1]);
//                }
                currentData.setBatteryVol(batteryPressure.floatValue());
                // 温度修正
//                currentData.setTc(temperatureCorrection.divide(new BigDecimal(10)).setScale(2, RoundingMode.HALF_UP).toString());
                currentData.setStatus(stateCode + "");
                currentData.setFaultCode(faultMsg);
                currentData.setWakeUpCycle(paramMap.get("uitv"));
//                dataVo.setFault(!StringUtils.isEmpty(faultMsg));
                currentData.setSignal(sign);
//                dataVo.setCommQuality(rsrp);
//                dataList.add(currentData);
                currentData.setFactoryName(factoryName);

                currentData.setReadTime(new Date(baseVo.getTimestamp()));
                currentData.setPanelDate(new Date(baseVo.getTimestamp()));

                AsynResult asynResult = new AsynResult();
                asynResult.setCode(ResultConstants.CODE_200);
                asynResult.setMsg(MqttUtil.successString);
//                asynResult.setSymbol("data");
                asynResult.setTimestamp(planTime.getTime());
                asynResult.setContent(currentData);
                asynResult.setIdentity(commTemperaturepressure.getId());
                MqttUtil.send(TemperaturePressureVo.TOPIC, asynResult);
            }

        }
    }

    public static void main(String[] args) {

//        String body = "{\"upPacketSN\":-1,\"upDataSN\":-1,\"topic\":\"v1/up/ad\",\"timestamp\":1726036935424,\"tenantId\":\"2000039707\",\"serviceId\":\"\",\"protocol\":\"lwm2m\",\"productId\":\"17139834\",\"payload\":{\"APPdata\":\"ZnVuYzp1cCxpZDoyNDEwMjA4OCx0eXA6Myxyc3JwOi04Ni4wLGVjbDowLHNucjozLjAsY2VsbGlkOjE2MDQ2NjczLGljY2lkOjg5ODYxMTI0MjEzMDI1OTc2OTkzLGltZWk6ODYxOTY5MDc0MTg0MDcyLGNzcToxOCxlY286QkUsbmJtb2Q6QkMyOEZGSFIwMUEwNCxuYmF0dGFjaDE6MTIwLG5iYXR0YWNoMjoxMjAsbmJyZWc6ODAsbmJjb246MTIwLG5icHNtOjEsbmJyOjgsbmJkZWxheTo1NzYscmVwOjM0LHJyZW06MzAwLFQxOlsyMS4xXSxldGltZToyMDI0MDkxMTA5NTE0NSxzdGE6MDEsdmVyOjE1LHJ0YzoyMDI0MDkxMTA5NTIwOSxzaXR2MTo1LHVpdHYxOjM2MCxzaXR2MjoyODgwLHVpdHYyOjI4ODAsaG90OjEwMDEwNDAxLGJhdDozLjY2MyxiYXR2OjMuMzAwLGxpZmU6Njc0NDYsVGM6MC4wLEhjOjAuMCxyZXNldDoxLHJlcGVycmNudDowLHJtYzoxMCxuYmk6MSxMRkRFVDowLGhyczowLGNlbnJlcHRpbWU6MCxzdGY6MSxzdGVtcDoyNS4wLHN0dWw6NDUuMCxzdGRsOjUuMCxjb21waWxlOjIwMjQtMDctMjRUMTYtNTQtMDQ=\"},\"messageType\":\"dataReport\",\"deviceType\":\"\",\"deviceId\":\"fa0fceb5f1db44c794fc7e4aee31110b\",\"assocAssetId\":\"\",\"IMSI\":\"undefined\",\"IMEI\":\"861969074184072\"}";
//        String body = "{\"upPacketSN\":-1,\"upDataSN\":-1,\"topic\":\"v1/up/ad\",\"timestamp\":1727426746085,\"tenantId\":\"2000039707\",\"serviceId\":\"\",\"protocol\":\"lwm2m\",\"productId\":\"17145003\",\"payload\":{\"APPdata\":\"ZnVuYzp1cCxpZDoyNDAwMDI4Nix0eXA6MSxyc3JwOi05MC4wLGVjbDowLHNucjo5LjAsY2VsbGlkOjEwNDc1NzIwMixpY2M6ODk4NjExMjMyNDgyNjEzMDg2MCxjc3E6MTYsb2xkczpGRSxuYm1vZDpCQzI4RkZIUjAxQTA0LHJ4dzoxMCxuYmRseToyLG5icmVzOjAscmVwOjc5LGNwcmQ6MCxzZXQ6MjUwLHNldHNyYzowLGN1cjoyNTAuMCxyY250OjAsbW9kZToxLHRhYzowLGFjbHM6MSxhY2x0OjQzMjAwLGJsb2NrOjAsYmxvY2tkZWFsOjAsbW90b3M6MCxjbHJjbnQ6MCxvdGltZTowLGQxazo1LGNvbnN0Y3VydmU6MCx0MTpbMjMuOV0sdDI6WzIzLjhdLHAxOlswLjI0OV0scDI6WzAuMjQ4XSxzdGE6ODk4MCxwYXI6MDAwMCx2ZXI6OTgwMSxydGM6MjAyNDA5MjYyMzU3MTMsY2l0djE6NSx1aXR2MTozNjAsY2l0djI6NSx1aXR2Mjo3MjAsaG90OjEwMTUwNDAxLG9mZmVyOjAwMDAwMDAwLGJhdDozLjY4MSxsaWZlOjU0MDE2LHQxYzowLjAsdDJjOjAuMCxwMWM6MC4wLHAyYzowLjAscmVzZXQ6MyxzZXR2Oi0xLjAsbG9nd3BvczowLGVsb2d3cG9zOjAsd2t0bTo1NDAxNix3a3RtMjozMCxyZmxhZzpmZixwc2VsOjEscGRseToxNSxscGFkOjAsbGNudDowLGNhbHJsOjAsb2RzZWM6MCxyZGlmZjowLHB1cGZsYWc6MCxyZXBlcnJjbnQ6MCxjYWxpYmVycjowLGNvbXBpbGU6MjAyMy0xMC0wN1QxOC01Mi0wMA0K\"},\"messageType\":\"dataReport\",\"deviceType\":\"\",\"deviceId\":\"ad65a26418f54dd9a332d7d0f90e538a\",\"assocAssetId\":\"\",\"IMSI\":\"undefined\",\"IMEI\":\"861969074552633\"}";
        String body = "{\"upPacketSN\":-1,\"upDataSN\":-1,\"topic\":\"v1/up/ad\",\"timestamp\":1734688021824,\"tenantId\":\"2000039707\",\"serviceId\":\"\",\"protocol\":\"lwm2m\",\"productId\":\"17175174\",\"payload\":{\"APPdata\":\"ZnVuYzp1cCxjaGVjazpBQUFBQUFBQSxpZDoyNDEyMjQ2Nyx0eXA6Myxyc3JwOi05Mi4wLGVjbDowLHNucjo4LjAsY2VsbGlkOjIxNTQ5Mjk0NCxpY2NpZDo4OTg2MTEyNDIxMzAyNjA1ODYxOSxpbWVpOjg2MTk2OTA3NDMyMzA2OCxjc3E6MTUsZWNvOkJFLG5ibW9kOkJDMjhGRkhSMDFBMDQsbmJhdHRhY2gxOjEyMCxuYmF0dGFjaDI6MTIwLG5icmVnOjgwLG5iY29uOjEyMCxuYnBzbToxLG5icjo4LG5iZGVsYXk6MTIscmVwOjIzNCxycmVtOjMwMCxuZnI6MCxuZnJfbjowLG5mcl9tOjg1MyxUMTpbMjMuNl0sZXRpbWU6MjAyNDEyMjAxNzM4Mzgsc3RhOjAwLHZlcjoxMTIyLHJ0YzoyMDI0MTIyMDE3NDY1NyxzaXR2MTo2MCx1aXR2MTo2MCxzaXR2MjoyODgwLHVpdHYyOjI4ODAsaG90OjEwMDEwNDAxLGJhdDozLjY2OSxiYXR2OjMuMzAwLGxpZmU6ODIwOTQsVGM6MC4wLEhjOjAuMCxyZXNldDoxLHJlcGVycmNudDowLHJtYzoxMCxuYmk6MCxMRkRFVDowLGhyczowLGFoZWFkOjAsY2VucmVwdGltZTowLFNjcjozMDAsc3RmOjAsY29tcGlsZToyMDI0LTEwLTEyVDE0LTAxLTI2DQo=\"},\"messageType\":\"dataReport\",\"deviceType\":\"\",\"deviceId\":\"a986374ac32b4360a75ae80fe51f4c0c\",\"assocAssetId\":\"\",\"IMSI\":\"undefined\",\"IMEI\":\"861969074323068\"}";
        ReportDataBaseVo baseVo = JSONObject.parseObject(body, ReportDataBaseVo.class);

        NbPlantService nbPlantService = new NbPlantService();
//        nbPlantService.receiveAEP_Temperature(baseVo, "HDRX");
        nbPlantService.receiveAEP_RU_Temperature(baseVo);



    }


    public void receiveRuna_TemperaturePressure(ReportDataBaseVo baseVo) {
        ReportDataDetailVo reportDataDetailVo = baseVo.getPayload();
        if (null != reportDataDetailVo && StringUtils.isNotBlank(reportDataDetailVo.getAPPdata())) {
            String decodeContent = new String(Base64Utils.decodeFromString(reportDataDetailVo.getAPPdata()));
            log.info("------nb-iot温压监测仪，上传数据解码后的内容为：" + decodeContent + "------getDeviceId: " + baseVo.getDeviceId());
            Map<String, String> paramMap = MqttSetUtils.getParsingArgumentsMap(decodeContent);
            //编号
            String serialNo = paramMap.get("id");
            LogUtil.getLogAndInfo(serialNo, "NB", JSON.toJSONString(baseVo));
            boolean validate = true;
            CommTemperaturepressure commTemperaturepressure = null;
            //设备厂家
            String type = MqttTemperaturePressureUtils.getValue(paramMap, "typ", "type");
            String factoryName = MqttSetUtils.getTemperaturePressureFactoryNameByType(type);
            if (StringUtils.isBlank(serialNo) || StringUtils.isBlank(factoryName)) {
                log.info("------nb-iot温压监测仪厂家或仪表编号不存在------");
                validate = false;
            } else {
                commTemperaturepressure = commTemperaturepressureRepository.findOne(Example.of(CommTemperaturepressure.builder().serial(serialNo)
                        .build())).orElse(null);
                if (commTemperaturepressure == null) {
                    log.error("数据库无数据---" + JSON.toJSONString(baseVo));
                    validate = false;
                }
            }

            if (!validate) {
                nbSendService.sendRtcCmd(baseVo.getDeviceId(), baseVo.getProductId(), mqttNbIotConfig.getAppKey()
                        , mqttNbIotConfig.getAppSecret(), mqttNbIotConfig.getTemperaturePressureMasterKey());
                return;
            }
            nbSendService.sendCmdToRunaTemperaturePressure(commTemperaturepressure.getId(), baseVo, serialNo, paramMap.get("sta"));

            List<TemperaturePressureCurrentData> temperaturePressureList = getTemperaturePressure(paramMap);

            log.debug("收到: {} 条, {}", temperaturePressureList.size(), JSON.toJSONString(temperaturePressureList));
            for (TemperaturePressureCurrentData currentData : temperaturePressureList) {
                currentData.setFactoryName(factoryName);
                currentData.setReadTime(new Date(baseVo.getTimestamp()));
                currentData.setPanelDate(new Date(baseVo.getTimestamp()));
                AsynResult asynResult = new AsynResult();
                asynResult.setCode(ResultConstants.CODE_200);
                asynResult.setMsg(MqttUtil.successString);
                asynResult.setTimestamp(currentData.getPlanTime().getTime());
                asynResult.setContent(currentData);
                asynResult.setIdentity(commTemperaturepressure.getId());
                MqttUtil.send(TemperaturePressureVo.TOPIC, asynResult);
                log.debug("{} {}", TemperaturePressureVo.TOPIC, JSON.toJSONString(asynResult));
            }

        }
    }



    public List<TemperaturePressureCurrentData> getTemperaturePressure(Map<String, String> paramMap) {
        //编号
        String serialNo = paramMap.get("id");
        //校时时间
        Date checkTime = UtilTime.StringToDate(paramMap.get("rtc"), "yyyyMMddHHmmss");

        String[] supplyTemperatureArray = MqttTemperaturePressureUtils.getArrayValue(paramMap, "T1", ARRAY_SPLIT);//供温
        String[] returnTemperatureArray = MqttTemperaturePressureUtils.getArrayValue(paramMap, "T2", ARRAY_SPLIT);//回温

        String[] supplyPressureArray = MqttTemperaturePressureUtils.getArrayValue(paramMap, "P1", ARRAY_SPLIT);//供压
        String[] returnPressureArray = MqttTemperaturePressureUtils.getArrayValue(paramMap, "P2", ARRAY_SPLIT);//回压

        String[] batteryPressureArray = MqttTemperaturePressureUtils.getArrayValue(paramMap, "bat", ARRAY_SPLIT);//电池电压，电压阈值/单位mV（供电电压_电压阈值）
        BigDecimal batteryPressure = null;
        if (batteryPressureArray.length > 0) {
            batteryPressure = stringToBigDecimal(batteryPressureArray[0]);
        }

        String sign = paramMap.get("csq");
        String rsrp = paramMap.get("rsrp");
        //状态字位对应
        String stateCode = paramMap.get("sta");// 转成十进制
        String citv = MqttTemperaturePressureUtils.getValue(paramMap, "citv1");//电池电压，电压阈值/单位mV（供电电压_电压阈值）
        BigDecimal sampling = null;
        if (StringUtil.isNotBlank(citv)) {
            sampling = stringToBigDecimal(citv);
        }
        String faultMsg = MqttTemperaturePressureUtils.getFaultMsgByCode(stateCode);
        int length = supplyTemperatureArray.length;

        List<TemperaturePressureCurrentData> currentDataList = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            TemperaturePressureCurrentData currentData = new TemperaturePressureCurrentData();
            currentData.setSerial(serialNo);
            currentData.setRsrp(rsrp);
            currentData.setFaultCode(faultMsg);
            if (null != sampling) {
                Date planTime = UtilTime.addMinute(checkTime, - sampling.intValue() * (length - i - 1));
                currentData.setPlanTime(planTime);
            } else {
                currentData.setPlanTime(checkTime);
            }
            if (supplyTemperatureArray != null && supplyTemperatureArray.length > 0) {
                currentData.setSupplyTemp(new BigDecimal(supplyTemperatureArray[i]).setScale(1, RoundingMode.HALF_UP).floatValue());
            }
            if (returnTemperatureArray != null && returnTemperatureArray.length > 0) {
                currentData.setReturnTemp(new BigDecimal(returnTemperatureArray[i]).setScale(1, RoundingMode.HALF_UP).floatValue());
            }
            if (supplyPressureArray != null && supplyPressureArray.length > 0) {
                currentData.setSupplyPre(stringToBigDecimal(supplyPressureArray[i]).multiply(BigDecimal.valueOf(1000)).floatValue());
            }
            if (returnPressureArray != null && returnPressureArray.length > 0) {
                currentData.setReturnPre(stringToBigDecimal(returnPressureArray[i]).multiply(BigDecimal.valueOf(1000)).floatValue());
            }
            String[] temperatureCorrectionArray = MqttTemperaturePressureUtils.getArrayValue(paramMap, "Tc", ARRAY_SPLIT);//温度修正，_左侧修正T1，_右侧修正T2
            if (null != temperatureCorrectionArray && temperatureCorrectionArray.length == 2) {
                currentData.setReturnTc(temperatureCorrectionArray[1]);
            } else {
                currentData.setReturnTc(MqttTemperaturePressureUtils.getValue(paramMap, "t2c"));
            }

            currentData.setBatteryVol(batteryPressure.floatValue());
            currentData.setStatus(stateCode + "");
            currentData.setFaultCode(faultMsg);
            currentData.setWakeUpCycle(paramMap.get("uitv"));
            currentData.setSignal(sign);

            currentDataList.add(currentData);
        }

        return currentDataList;
    }


    private BigDecimal stringToBigDecimal(String string) {
        if (StringUtils.isNotBlank(string)) {
            return new BigDecimal(string).setScale(2, RoundingMode.HALF_UP);
        }
        return null;
    }

    private BigDecimal stringToBigDecimal(String string, int scale) {
        if (StringUtils.isNotBlank(string)) {
            return new BigDecimal(string).setScale(scale, RoundingMode.HALF_UP);
        }
        return null;
    }

    public Integer getPowerType(String powerType) {
        return powerType == null || powerType.length() < 12
                ? null
                : Integer.valueOf(powerType.substring(4, 5));
    }

    public void receiveAEP_BuildMeter(ReportDataBaseVo baseVo) {
        ReportDataDetailVo reportDataDetailVo = baseVo.getPayload();
        if (null != reportDataDetailVo && StringUtils.isNotBlank(reportDataDetailVo.getAPPdata())) {
            String decodeContent = new String(Base64Utils.decodeFromString(reportDataDetailVo.getAPPdata()));
            log.info("------nb-iot楼表，上传数据解码后的内容为：" + decodeContent + "------getDeviceId: " + baseVo.getDeviceId());
            Map<String, String> paramMap = MqttSetUtils.getParsingArgumentsMap(decodeContent);
            //编号
            String serialNo = paramMap.get("id");
            LogUtil.getLogAndInfo(serialNo, "NB", JSON.toJSONString(baseVo));
            String typ = paramMap.get("typ");
            String sample = paramMap.get("rp");
            boolean validate = true;
            CommMeter commMeter = null;
            //设备厂家
            commMeter = commMeterRepository.findOne(Example.of(CommMeter.builder().serial(serialNo)
                    .build())).orElse(null);
            if (commMeter == null) {
                log.error("数据库无数据---" + JSON.toJSONString(baseVo));
                validate = false;
            }

            if (!validate) {
                nbSendService.sendRtcCmd(baseVo.getDeviceId(), baseVo.getProductId(), mqttNbIotConfig.getAppKey()
                        , mqttNbIotConfig.getAppSecret(), mqttNbIotConfig.getBuildMeterMasterKey(baseVo.getProductId()));
                return;
            }
            nbSendService.sendCmdToMeter(commMeter.getId(), baseVo, sample);

            String sign = paramMap.get("csq");
            String rsrpStr = paramMap.get("rsrp");
            BigDecimal rsrp = null;
            if (StringUtils.isNotBlank(rsrpStr)) {
                rsrp = new BigDecimal(rsrpStr).setScale(2, RoundingMode.HALF_UP);
            }
            //校时时间
//            Date checkTime = UtilTime.StringToDate(paramMap.get("rtc"), "yyyyMMddHHmmss");
            //解析多条采集数据
            List<MqttBuildMeterDataVo> dataList = new BuildMeterDecode().heatMeterDecode(paramMap.get("data"));
            //处理业务
            BigDecimal batteryVolt = Objects.requireNonNull(stringToBigDecimal(paramMap.get("volt"), 3)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
            for (MqttBuildMeterDataVo mqttBuildMeterDataVo : dataList) {
                HotMeterVO hotMeterVO = new HotMeterVO();
                hotMeterVO.setMeterSerial(serialNo);
                hotMeterVO.setWakeUpCycle(sample);
                hotMeterVO.setRsrp(String.valueOf(rsrp));
                hotMeterVO.setSignInfo(sign);
                hotMeterVO.setBatteryVol(batteryVolt.floatValue());

                hotMeterVO.setReadDate(mqttBuildMeterDataVo.getReadDate());
                hotMeterVO.setMeterDate(mqttBuildMeterDataVo.getMeterDate());
                hotMeterVO.setFlow(mqttBuildMeterDataVo.getFlow());
                hotMeterVO.setPower(floatToDecimal(mqttBuildMeterDataVo.getHeat()));
                hotMeterVO.setAccFlow(mqttBuildMeterDataVo.getAccFlow());
                hotMeterVO.setAccHeat(floatToDecimal(mqttBuildMeterDataVo.getAccHeat()));
                hotMeterVO.setWorkTime(intToDecimal(mqttBuildMeterDataVo.getWorkTime()));
                hotMeterVO.setReturnTemp(floatToDecimal(mqttBuildMeterDataVo.getOutTemperature()));
                hotMeterVO.setSupplyTemp(floatToDecimal(mqttBuildMeterDataVo.getInTemperature()));
                hotMeterVO.setStatus(mqttBuildMeterDataVo.getMeterStatus());
                hotMeterVO.setFaultCode(RunaEquDataAnalysis.heatMeterFaults(hotMeterVO.getStatus()));

                AsynResult asynResult = new AsynResult();
                asynResult.setCode(ResultConstants.CODE_200);
                asynResult.setMsg(MqttUtil.successString);
//                asynResult.setSymbol("data");
//                asynResult.setTimestamp(checkTime.getTime());
                asynResult.setContent(hotMeterVO);
                asynResult.setIdentity(commMeter.getId());
                MqttUtil.send(HotMeterVO.TOPIC, asynResult);
            }

        }
    }

    private Float floatToDecimal(Float ft) {
        return ft == null ? null : BigDecimal.valueOf(ft).setScale(2, RoundingMode.HALF_UP).floatValue();
    }

    private Integer intToDecimal(Integer it) {
        return it == null ? null : BigDecimal.valueOf(it).setScale(2, RoundingMode.HALF_UP).intValue();
    }

    public void receiveAEP_BuildValve_Te(ReportDataBaseVo baseVo) {
        ReportDataDetailVo reportDataDetailVo = baseVo.getPayload();
        Long timestamp = baseVo.getTimestamp();
        if (null != reportDataDetailVo && StringUtils.isNotBlank(reportDataDetailVo.getAPPdata())) {
            String decodeContent = new String(Base64Utils.decodeFromString(reportDataDetailVo.getAPPdata()));
            log.info("------nb-iot楼阀，上传数据解码后的内容为：" + decodeContent + "------getDeviceId: " + baseVo.getDeviceId());
            Map<String, String> paramMap = MqttSetUtils.getParsingArgumentsMap(decodeContent);
            //编号
            String serialNo = paramMap.get("id");
            LogUtil.getLogAndInfo(serialNo, "NB", JSON.toJSONString(baseVo));
            String typ = paramMap.get("typ");
            CommTemperaturepressure commValve = null;
            boolean validate = true;
            commValve = commTemperaturepressureRepository.findOne(Example.of(CommTemperaturepressure.builder().serial(serialNo)
                    .build())).orElse(null);
            if (commValve == null) {
                log.error("数据库无数据---" + JSON.toJSONString(baseVo));
                validate = false;
            }

            if (!validate) {
                nbSendService.sendRtcCmd(baseVo.getDeviceId(), baseVo.getProductId(), mqttNbIotConfig.getAppKey()
                        , mqttNbIotConfig.getAppSecret(), mqttNbIotConfig.getBuildValveTtemperaturePressureMasterKey());
                return;
            }
            nbSendService.sendCmdToBuildValveTe(commValve.getId(), baseVo, paramMap.get("uitv1"));


//            if (!MqttSetUtils.checkEquDataValid(redisUtil, "楼阀", typ, serialNo)) {
//                log.info("----nb-iot楼阀，编号：{}-距离上次接收数据未超过2分钟，此条数据废弃----", serialNo);
//                return;
//            }
            //校时时间
            Date checkTime = UtilTime.StringToDate(paramMap.get("rtc"), "yyyyMMddHHmmss");
//            List<MqttBuildValveDataVo> dataList = new ArrayList<>();
            String supplyTemStr = MqttBuildValveUtils.filterStr(paramMap.get("t1"));
            String[] supplyTemArray = supplyTemStr.split(ARRAY_SPLIT);
            String returnTemStr = MqttBuildValveUtils.filterStr(paramMap.get("t2"));
            String[] returnTemArray = returnTemStr.split(ARRAY_SPLIT);
            String supplyPreStr = MqttBuildValveUtils.filterStr(paramMap.get("p1"));
            String[] supplyPreArray = null;
            if (StringUtils.isNotBlank(supplyPreStr)) {
                supplyPreArray = supplyPreStr.split(ARRAY_SPLIT);
            }
            String returnPreStr = MqttBuildValveUtils.filterStr(paramMap.get("p2"));
            String[] returnPreArray = null;
            if (StringUtils.isNotBlank(returnPreStr)) {
                returnPreArray = returnPreStr.split(ARRAY_SPLIT);
            }
            BigDecimal actualOpening = stringToBigDecimal(paramMap.get("cur"));
            BigDecimal controlOpening = stringToBigDecimal(paramMap.get("set"));
            String version = paramMap.get("ver");
            BigDecimal batteryVolt = stringToBigDecimal(paramMap.get("bat"), 3);
            String sign = paramMap.get("csq");
            String rsrp = paramMap.get("rsrp");
            //本地还是远程
            String controlModel = null;
            String model = paramMap.get("mode");
            if ("1".equals(model)) {
                controlModel = "远程";
            } else if ("0".equals(model)) {
                controlModel = "本地";
            }
            // String powerTime = paramMap.get("life");
            //采样周期
            String citv = paramMap.get("uitv1");
            int sampling = Integer.parseInt(citv);
            String stateCode = paramMap.get("sta");
            int length = supplyTemArray.length;
            for (int i = 0; i < length; i++) {
//                ValveVO valveVO = new ValveVO();
                TemperaturePressureCurrentData valveVO = new TemperaturePressureCurrentData();
                valveVO.setSerial(serialNo);
//                valveVO.setStatus(stateCode);
//                valveVO.setFaultCode(faultMsg);
                if (actualOpening != null) {
//                    valveVO.setActOpen(actualOpening.floatValue());
//                    valveVO.setRemoteSet(controlOpening.floatValue());
                }

                valveVO.setReadTime(UtilTime.addMinute(checkTime, -sampling * (length - i - 1)));
                valveVO.setPanelDate(UtilTime.addMinute(checkTime, -sampling * (length - i - 1)));
//                valveVO.setActualValue(actualOpening);
//                valveVO.setTargetValue(controlOpening);
                valveVO.setSupplyTemp(stringToBigDecimal(supplyTemArray[i]).floatValue());
                valveVO.setReturnTemp(stringToBigDecimal(returnTemArray[i]).floatValue());
//                if (supplyPreArray != null && supplyPreArray.length > 0) {
//                    valveVO.setSupplyPre(stringToBigDecimal(supplyPreArray[i]).floatValue());
//                }
//                if (returnPreArray != null && returnPreArray.length > 0) {
//                    valveVO.setReturnPre(stringToBigDecimal(returnPreArray[i]).floatValue());
//                }
                valveVO.setStatus(stateCode);
//                valveVO.setLR(ValveVO.LREnum.valueOf(controlModel));
                valveVO.setSignal(sign);
                valveVO.setWakeUpCycle(citv);
                valveVO.setRsrp(rsrp);
//                valveVO.setPowerType(powerType);
//                dataVo.setControlModel(controlModel);
                valveVO.setBatteryVol(batteryVolt.floatValue());
//                valveVO.setPowerType(powerType);
//                valveVO.setSoftVersion(version);
//                dataList.add(dataVo);
                if (null != supplyPreArray && supplyPreArray.length > 0 && i == 0) {
//                    valveVO.setSupplyPre(stringToBigDecimal(supplyPreArray[i], 2).floatValue());
                    valveVO.setSupplyPre(Float.parseFloat(supplyPreArray[0]) * 1000);
                }
                if (null != returnPreArray && returnPreArray.length > 0 && i == 0) {
//                    valveVO.setReturnPre(stringToBigDecimal(returnPreArray[i], 2).floatValue());
                    valveVO.setReturnPre(Float.parseFloat(returnPreArray[0]) * 1000);
                }
                AsynResult asynResult = new AsynResult();
                asynResult.setCode(ResultConstants.CODE_200);
                asynResult.setMsg(MqttUtil.successString);
//                asynResult.setSymbol("data");
                asynResult.setTimestamp(UtilTime.addMinute(new Date(timestamp), -sampling * (length - i - 1)).getTime());
                asynResult.setContent(valveVO);
                asynResult.setIdentity(commValve.getId());
                MqttUtil.send(TemperaturePressureVo.TOPIC, asynResult);

            }
        }
    }

    /*
     *
     */
    @Test
    public void test() {
        String[] split = "0.314".split(ARRAY_SPLIT);
        System.out.println(24);
        BigDecimal bigDecimal = stringToBigDecimal(split[0]);
        System.out.println(bigDecimal);

        float v = Float.parseFloat(split[0]) * 1000;
        System.out.println(v * 1000);
    }
}
